package com.xwj.auction.service;

import com.xwj.auction.dao.AuctionItemMapper;
import com.xwj.auction.dao.AuctionItemRecordMapper;
import com.xwj.auction.dao.RobAuctionItemOrderMapper;
import com.xwj.auction.domain.AuctionItem;
import com.xwj.auction.domain.AuctionItemRecord;
import com.xwj.auction.domain.RobAuctionItemOrder;
import com.xwj.auction.util.DateUtil;
import com.xwj.common.dto.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xwj
 * @date 2020/5/8
 */
@Service
public class AuctionItemService {
    @Autowired
    private AuctionItemMapper auctionItemMapper;
    @Autowired
    private AuctionItemRecordMapper auctionItemRecordMapper;
    @Autowired
    private RobAuctionItemOrderMapper robAuctionItemOrderMapper;

    private final Lock lock = new ReentrantLock(true);

    @Transactional(rollbackFor = Exception.class)
//    @ServiceLock
    public BaseResponse rob(Integer userId, Long id) {
        // 1、校验抢拍时间是否过期 TODO
//        AuctionItem auctionItem = auctionItemMapper.selectForUpdate(id);
        AuctionItem auctionItem = auctionItemMapper.select(id);
        if (auctionItem != null) {
            Date now = new Date();
            // 2、校验商品状态
            if (auctionItem.getStatus().equals(0)) {
                // 判断当前用户是否抢拍过
                if(robAuctionItemOrderMapper.selectByItemIdAndUseId(id, userId) == 0) {
                    // 3、校验商品是否已被抢且他人是否已付款
                    // 若已抢拍者规定时间内未付款，他人仍然可抢，并修改已抢拍者订单状态
                    RobAuctionItemOrder record = robAuctionItemOrderMapper.selectLatestOrder(auctionItem.getId());
                    if(record != null) {
                        if(record.getPayDeadTime().after(now) || record.getStatus().equals(2)) {
                            return BaseResponse.error("抢拍商品已被抢");
                        }
                        if (record.getPayDeadTime().before(now)) {
                            // 他人抢拍订单在规定时间内未付款，取消他人抢拍订单
                            robAuctionItemOrderMapper.cancelOrderById(record.getId());
//                            robAuctionItemOrderMapper.cancelOrderByVersion(record.getId(), record.getVersion(), 1);
                        }
                    }
                    // 更新最新抢拍支付截止时间
//                    LocalDateTime now = LocalDateTime.now();
                    Date lastRobPayDeadTime = DateUtil.plusSeconds(now, 15);
                    int result = auctionItemMapper.updateLastRobPayDeadTime(auctionItem.getId(), auctionItem.getLastRobPayDeadTime(), lastRobPayDeadTime);
//                int result = robAuctionItemOrderMapper.insert(order);
//                int result = auctionItemMapper.updateStatus(id);
//                int result = auctionItemMapper.updateStatusByVersion(id)
                    if (result == 1) {
                        // 可抢，生成抢拍订单
                        RobAuctionItemOrder order = new RobAuctionItemOrder();
                        order.setUserId(userId);
                        order.setItemId(id);
                        order.setCreateTime(now);
                        order.setStatus(0);
                        order.setPayDeadTime(lastRobPayDeadTime);
                        robAuctionItemOrderMapper.insert(order);
                        System.out.println("时间："+LocalDateTime.now()+"用户：" + userId + "抢拍商品：" + id + "成功");
                        return BaseResponse.success();
                    }
                }
                return BaseResponse.error("抱歉，您不能重复抢拍此商品");
            }
            return BaseResponse.error("抢拍商品已被抢");
        } else {
            return BaseResponse.error("抢拍商品不存在");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public BaseResponse raise(Integer userId, Long id) {
        AuctionItem auctionItem = auctionItemMapper.select(id);
        if (auctionItem != null) {
            if (auctionItem.getStatus().equals(0)) {
                Integer price = auctionItem.getPrice() + 100;
                int result = auctionItemMapper.updatePrice(id, auctionItem.getPrice(), price);
                if (result == 1) {
                    System.out.println("商品：" + id + "，用户：" + userId + "出价" + price + "成功");
                    // 保存竞拍记录
                    AuctionItemRecord record = new AuctionItemRecord();
                    record.setUserId(userId);
                    record.setItemId(id);
                    record.setPrice(price);
                    record.setCreateTime(LocalDateTime.now());
                    auctionItemRecordMapper.insert(record);
                    return BaseResponse.success(price);
                } else {
                    System.out.println("商品：" + id + "，用户：" + userId + "出价" + price + "失败，当前价格已变更，请重新出价");
                    return BaseResponse.error("当前价格已变更，请重新出价");
                }
            } else {
                System.out.println("商品：" + id + "已拍出");
                return BaseResponse.error("竞拍商品已拍出");
            }
        } else {
            return BaseResponse.error("竞拍商品不存在");
        }
    }
}
